﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WinFormDataBinding
{
    public partial class MainForm : Form
    {
        private CountriesTownsDataContext context;
        private int continentId;

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            CountriesTownsDataContext.GlobalLog = new TextBoxWriter(logTxtb);
            Init();     
        }

        private void Init()
        {
            context = new CountriesTownsDataContext();
            continentBindingSource.DataSource = context.Continents;
            continentId = (int)continentsListBox.SelectedValue;
            countryBindingSource.DataSource = context.Countries.Where(x => x.ContinentId == continentId);
            ShowStatus("Data Loaded");
        }

        private void firstBtn_Click(object sender, EventArgs e)
        {
            countryBindingSource.MoveFirst();
        }

        private void previousBtn_Click(object sender, EventArgs e)
        {
            countryBindingSource.MovePrevious();
        }

        private void nextBtn_Click(object sender, EventArgs e)
        {
            countryBindingSource.MoveNext();
        }

        private void lastBtn_Click(object sender, EventArgs e)
        {
            countryBindingSource.MoveLast();
        }

        private void cancelBtn_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void okBtn_Click(object sender, EventArgs e)
        {
            context.SubmitChanges();
            this.Close();
        }

        private void ShowStatus(string statusText)
        {
            toolStripStatusLabel.Text = statusText;
        }

        private void continentsListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (continentsListBox.SelectedValue != null)
            {
                continentId = (int)continentsListBox.SelectedValue;
                countryBindingSource.DataSource = context.Countries.Where(x => x.ContinentId == continentId);
            }
        }

        private void saveBtn_Click(object sender, EventArgs e)
        {
            context.SubmitChanges();
            ShowStatus("Changes Saved");
        }

        private void realoadBtn_Click(object sender, EventArgs e)
        {
            Init();
            ShowStatus("Data Reloaded");
        }
    }
}
